<template>
	<view class="page">
		<uni-forms ref="form" :model="formData" validateTrigger="bind" v-show="formData.course_id" label-width="100px">
		  <uni-forms-item name="course_id" label="开通课程" required>
			  <text v-if="course">{{course.title}}</text>
		  </uni-forms-item>
		  <uni-forms-item name="mobile" label="手机号" required>
			 <uni-easyinput v-model="formData.mobile" placeholder="请输入你的手机号" style="width: 200px;"></uni-easyinput>
		  </uni-forms-item>
		  <view class="uni-button-group">
		    <button type="primary" class="uni-button" style="width: 100px;margin-right: 10px;" @click="submit()">确定</button>
		    <button class="uni-button" style="width: 100px;"  @click="close()">关闭</button>
		  </view>
		</uni-forms>
		<view v-show="isFail" style="text-align: center;font-weight: 800;height: 100px;line-height: 50px;">
			<uni-icons type="info" size="34"></uni-icons><br />
			扫码失败,重新扫码
		</view>
	</view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/mydb-course-catch.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'mydb-course-catch';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "course_id": "",
        "chapter_id": "",
        "invite": true,
        "mobile": ""
      }
      return {
        formData,
		course:null,
		isFail:false,
        formOptions: {},
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
	onLoad(e) {
		uni.showLoading()
		let curTime=new Date().getTime()
		if(e.time<curTime-600000){
			this.isFail=true
			uni.hideLoading()
			uni.showToast({
			  title: '二维码失效,重新扫码',
			  icon:'none'
			})
			return
		}else{
			uni.hideLoading()
			this.formData.course_id=e.id
			db.collection('mydb-course-list').doc(e.id).get().then((res)=>{
				this.course=res.result.data[0]
			})
			document.addEventListener('WeixinJSBridgeReady', function() {
				WeixinJSBridge.call('closeWindow');
			}, false);
		}
	},
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      close(){
		  WeixinJSBridge.call('closeWindow');
	  },
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).add({
			mobile:value.mobie,
			invite:true,
			course_id:value.course_id
		}).then((res) => {
          uni.showToast({
            title: '开通成功'
          })
          setTimeout(() => WeixinJSBridge.call('closeWindow'), 1500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      }
    }
  }
</script>

<style scoped>
	page,.page{
		padding: 10px;
	}
	.page{
		background-color: #f1f1f1;
		border-radius: 15px;
		position: fixed;
		top: 20%;
		left: 5%;
		width: 90%;
		padding: 20px;
		box-sizing: border-box;
	}
</style>